package com.food.foodapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.food.foodapi.instans.Result;
import com.food.foodapi.mapper.ArticleMapper;
import com.food.foodapi.mapper.CollectionMapper;
import com.food.foodapi.mapper.TypeMapper;
import com.food.foodapi.mapper.UserMapper;
import com.food.foodapi.model.entity.Article;
import com.food.foodapi.model.entity.Collection;
import com.food.foodapi.model.entity.User;
import com.food.foodapi.model.result.ArticleResult;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 92110
 */
@RestController
@RequestMapping("/article")
@SuppressWarnings("ALL")
public class ArticleController {

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private TypeMapper typeMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CollectionMapper collectionMapper;

    @PostMapping("/add")
    public Result addArticle(@RequestBody Article article, HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error(401, "请先登录");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return Result.error(401, "用户不存在");
        }
        article.setAuthor(user.getId());

        articleMapper.insert(article);
        return Result.success("添加成功");
    }

    @GetMapping("/home/list")
    public Result listArticle() {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.select("id", "title", "image_url");
        wrapper.eq("shenhe_status", "已通过");
        wrapper.last("order by rand() limit 8");
        List<Article> articles = articleMapper.selectList(wrapper);
        // 随机抽8个对象返回
        Collections.shuffle(articles);
        return Result.success(articles);
    }

    @GetMapping("/get/detail/{id}")
    public Result getArticle(@PathVariable String id, HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error(401, "请先登录");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return Result.error(401, "用户不存在");
        }

        Article article = articleMapper.selectById(id);
        if (article == null) {
            return Result.notFound("文章不存在");
        }
        if (article.getType() != null) {
            article.setType(typeMapper.selectById(article.getType()).getName());
        }
        article.setAuthor(userMapper.selectById(article.getAuthor()).getNickname());
        ArticleResult result = new ArticleResult();
        BeanUtils.copyProperties(article, result);
        Collection collection = collectionMapper.selectOne(new QueryWrapper<Collection>()
                .eq("user_id", user.getId()).eq("article_id", id));
        if (collection == null) {
            result.setCollection(false);
        } else {
            result.setCollection(true);
        }
        return Result.success(result);
    }

    @PutMapping("/update")
    public Result updateArticle(@RequestBody Article article) {
        articleMapper.updateById(article);
        return Result.success("更新成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteArticle(@PathVariable String id) {
        articleMapper.deleteById(id);
        return Result.success("删除成功");
    }

    @GetMapping("/get/type/{type}")
    public Result getArticleByType(@PathVariable String type) {

        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.select("id", "title", "description", "image_url", "create_time", "type", "author");
        wrapper.eq("type", type).eq("shenhe_status", "已通过");
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(articles);
    }

    @GetMapping("/get/bankuai/{bankuai}")
    public Result getAllArticle(@PathVariable String bankuai) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.select("id", "title", "description", "image_url", "create_time", "bankuai", "author");
        wrapper.eq("bankuai", bankuai).eq("shenhe_status", "已通过");
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(articles);
    }

    @GetMapping("/get/search/{keyword}")
    public Result getArticleById(@PathVariable String keyword) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.select("id", "title", "description", "image_url", "create_time", "bankuai", "author");
        wrapper.like("title", keyword).eq("shenhe_status", "已通过");
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(articles);
    }

    @GetMapping("/collection/{id}")
    public Result collectionArticle(@PathVariable String id, HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error(401, "请先登录");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return Result.error(401, "用户不存在");
        }
        Collection collection = new Collection(id, user.getId());
        collectionMapper.insert(collection);
        return Result.success("收藏成功");
    }

    @GetMapping("/collection/count/{id}")
    public Result collectionCount(@PathVariable String id) {
        Integer count = Math.toIntExact(collectionMapper.selectCount(new QueryWrapper<Collection>().eq("article_id", id)));
        return Result.success(count);
    }

    @GetMapping("/collection/list")
    public Result collectionList(HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error(401, "请先登录");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return Result.error(401, "用户不存在");
        }
        List<Collection> collections = collectionMapper.selectList(new QueryWrapper<Collection>()
                .eq("user_id", user.getId()));
        List<Article> articles = new ArrayList<>();
        for (Collection collection : collections) {
            Article article = articleMapper.selectById(collection.getArticleId());
            articles.add(article);
        }
        return Result.success(articles);
    }

    @GetMapping("/collection/delete/{id}")
    public Result collectionDeleteArticle(@PathVariable String id, HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error(401, "请先登录");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return Result.error(401, "用户不存在");
        }
        collectionMapper.delete(new QueryWrapper<Collection>().eq("user_id", user.getId()).eq("article_id", id));
        return Result.success("删除成功");
    }
}
